package com.ljh.lottery.service.impl;

import com.ljh.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.ljh.lottery.common.exception.ServiceException;
import com.ljh.lottery.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: Themberfue
 * @date: 2025/4/11 11:00
 * @description:
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String uploadPic(MultipartFile multipartFile) {
        // TODO 1. 创建目录
        File dir = new File(localPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // TODO 2. 创建索引
        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));

        // TODO 3. 存入服务器
        try {
            multipartFile.transferTo(new File(localPath + fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return fileName;
    }
}
